//
//  YROAuthViewController.swift
//  新浪微博
//
//  Created by Viper on 16/6/26.
//  Copyright © 2016年 Viper. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
class YROAuthViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        
        setupNav()
        
    }
    
    override func loadView() {
        
        view = webViwe
    }
    
    
    //MARK: - 设置视图
   private func setupUI(){
        view.backgroundColor = UIColor.whiteColor()
        
    }
    //MARK: - 设置导航栏
    private func setupNav(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(YROAuthViewController.cancelClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(YROAuthViewController.oauthFillClick))
        navigationItem.title = "OAuth登录"
 
    }
  //MARK: - 监听事件
    @objc private func cancelClick(){
        
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    @objc private func oauthFillClick(){
        
        let jsString = "document.getElementById('userId').value='656731375@qq.com',document.getElementById('passwd').value='liuyuru++1129'"
        // JS注入
        webViwe.stringByEvaluatingJavaScriptFromString(jsString)
       
    }

    
    //MARK: -懒加载控件
    
    private  lazy var webViwe : UIWebView = {
       
        let view = UIWebView()
        
        view.delegate = self
        
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(REDIRECT_URI)")
        
//        print(url)
      
        let request = NSURLRequest(URL: url!)
        
        view.loadRequest(request)
        
        return view
     
        
    }()
   
}

extension YROAuthViewController : UIWebViewDelegate{
    
    //开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
        
    }
    //加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
        
    }
    //将要加载的request
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //如果返回true 继续加载  如果返回false 停止加载  默认不实现 代表true
        
        let urlString = request.URL?.absoluteString
     
        //判断url是否有值  前缀是我们的回调页
        if let u = urlString where u.hasPrefix(REDIRECT_URI) {
            //请求参数键值对
            let quest = request.URL?.query
            
            if let q = quest {
                
                let code = q.substringFromIndex("code=".endIndex)
//                print("这里这里这里\(code)")
                loadUserAccount(code)
                
                return false
            }
        }
       
        return true
        
    }
    //加载出错
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
    }
}
extension YROAuthViewController {
    
    func loadUserAccount(code:String){
        
        YRNetwoekTools.sharedTools.oauthUserAccount(code, success: { (respones) in
        
            guard let res = respones as? [String : AnyObject] else {

                return
            }
            
            let userAccount = YRUserAccount(dict: res)
            
            self.loadUserInfo(userAccount)
            
            
            }) { (error) in
            
                print("失败\(error)")
                
                SVProgressHUD.showErrorWithStatus("请求失败")
                
        }
    }
    
    func loadUserInfo(userAccount : YRUserAccount){
        
        YRNetwoekTools.sharedTools.oauthLoadUserInfo(userAccount, success: { (respones) in

            guard let res = respones as? [String : AnyObject] else {
                
                return
            }
            
            userAccount.avatar_large = res["avatar_large"] as? String
            userAccount.screen_name = res["screen_name"] as? String
            //通过归档保存数据
            YRUserAccountTools.sharedTools.saveUserAccount(userAccount)
           
            self.dismissViewControllerAnimated(false, completion: { 
                
                SVProgressHUD.dismiss()
                //发送通知告知appdelegate 切换根控制器rootVC = welcome
                
                NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootVcNoti, object: nil)
                
            })
            
            }) { (error) in
        
              print("\(error)")
            
        }
    }
}

